<template>
  <div v-for="(section, index) in questionnaire.sections" :key="index">
    <h3>{{ section.title }}</h3>
    <div v-for="question in section.questions" :key="question.id" class="question-card" :data-question-id="question.id">
      <div>
        <p class="question_description">{{ question.id }}.{{ question.description }}</p>
        <p>{{ question.text }}</p>
        <el-radio-group v-model="answers[question.id]">
          <el-radio v-for="(option, idx) in question.options" :key="idx" :label="option">
            {{ option }}
          </el-radio>
        </el-radio-group>
      </div>
    </div>
  </div>


</template>


<script>
import { ref, reactive, onMounted, defineEmits } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import questionnaire from '@/assets/js/radio';
import api from '@/assets/js/api.js'; // 导入公用接口文件

export default {
  name: 'Questionnaire',
  props: {
    companyId: Array,
    companyName: Array,
    textareaValue: String,
    name: String,
  },
  setup(props) {
    console.log("公司 ID:", props.companyId);  
    console.log("已选系统名称:", props.companyName);  
    console.log("公司名称:", props.name);  
    console.log("备注:", props.textareaValue); 

    const parames = reactive({
      selectCompany: '',
      selectSystem: [],
      textareaValue: '',
    });
    console.log(parames.selectSystem);
    // 定义数据
    const parames1 = ref({
      selectSystem: [],
      selectedNames: [],
    });

    // 新增变量 isSystemSelected 用于检查是否已选择系统
    const isSystemSelected = ref(false);
    const answers = reactive({});
    const selectedSystemMap = reactive([]); // 追踪每个题目选项的系统选择
    const questionSystemSelections = reactive({}); // 追踪每个题目中已选择的系统
    const emit = defineEmits();

    // 初始化 answers 回显
    const selectSystemDatas = ref([]);
    const dataName = {
      "unitName": "国网四川省电力公司天府新区供电公司"
    };
    const fetchDataAnsers = async () => {
      try {
        let data = await api.post('/system/questionnaire/get', dataName);
        console.log('获取数据', data);
        parames.selectCompany = data.unitName;
        parames.selectSystem = data.systemNames;
        selectSystemDatas.value = data.value; // 赋值
        parames1.value.selectSystem = data.systemNames;
        initializeSelectedSystems(data.value);
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };

    // 初始化已选系统到 selectedSystemMap 回显
    const initializeSelectedSystems = (selectSystemDatas) => {
      console.log(selectSystemDatas);

      if (!selectSystemDatas || Object.keys(selectSystemDatas).length === 0) return;

      Object.entries(selectSystemDatas).forEach(([questionId, options]) => {
        answers[questionId] = Object.keys(options);

        Object.entries(options).forEach(([option, systems]) => {
          const key = `${questionId}-${option}`;
          selectedSystemMap[key] = systems || [];
        });
        // });
        // Object.entries(selectSystemDatas).forEach(([questionId, options]) => {
        //   // 初始化问题的选项选择
        //   answers[questionId] = Object.keys(options);

        //   // 初始化每个选项的系统选择
        //   Object.entries(options).forEach(([option, systems]) => {
        //     const key = `${questionId}-${option}`;
        //     selectedSystemMap[key] = systems;
        //   });

        console.log(answers[questionId]);

        // 检查每个勾选的选项是否有系统选中，如果没有则取消勾选
        // answers[questionId].forEach((option) => {
        //   const key = `${questionId}-${option}`;

        //   if (!selectedSystemMap[key] || selectedSystemMap[key].length === 0) {
        //     const index = answers[questionId].indexOf(option);
        //     if (index > -1) answers[questionId].splice(index, 1); // 取消该选项的勾选状态
        //   }
        // });
      });
    };

    // 获取系统
    const selectSystemOptions = ref([]);
    const dataSystem = ref(null);
    const fetchDataSystem = async () => {
      try {
        dataSystem.value = await api.get('/system/system/list');
        selectSystemOptions.value = dataSystem.value.list; // 赋值

      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };
    // 获取企业
    const selectCompanyOption = ref([]); // 确保使用 ref
    const dataCompany = ref(null);

    const fetchDataCompany = async () => {
      try {
        dataCompany.value = await api.get('/system/unit/list');
        selectCompanyOption.value = dataCompany.value.list; // 赋值
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };


    const handleSelectSystemChange = (value) => {
      parames1.value.selectSystem = value;
      console.log("parames.selectSystem (IDs):", parames1.value.selectSystem);
      isSystemSelected.value = value.length > 0; // 检查是否已选择至少一个系统

      // 根据 ID 查找对应的名称
      parames1.value.selectedNames = parames1.value.selectSystem.map((id) => {
        const matchedItem = selectSystemOptions.value.find((item) => item.systemName === id);
        return matchedItem ? matchedItem.id : null;
      });

      console.log("Selected Names:", parames1.value.selectedNames);
    };


    // 判断某系统选项是否已被当前题目其他选项选择，只有在同一题目的其他题项中该系统被选择时才禁用
    const isSystemDisabled = (questionId, system, option) => {
      return questionSystemSelections[questionId]?.includes(system) && !selectedSystemMap[`${questionId}-${option}`]?.includes(system);
    };


    const updateSystemSelection = (questionId, option, system) => {

      const key = `${questionId}-${option}`;

      if (!selectedSystemMap[key]) selectedSystemMap[key] = [];
      if (!questionSystemSelections[questionId]) questionSystemSelections[questionId] = [];

      if (selectedSystemMap[key].includes(system)) {
        // 移除系统
        selectedSystemMap[key] = selectedSystemMap[key].filter((item) => item !== system);
        questionSystemSelections[questionId] = questionSystemSelections[questionId].filter((item) => item !== system);
      } else {
        // 添加系统
        selectedSystemMap[key].push(system);
        questionSystemSelections[questionId].push(system);
      }

      // 检查该选项是否至少有一个系统被选中
      if (selectedSystemMap[key].length > 0) {
        // 如果该选项有系统被选中，确保它在 answers 中被勾选
        if (!answers[questionId].includes(option)) {
          answers[questionId].push(option);
        }
      } else {
        // 如果没有系统被选中，检查其他选项的系统状态
        const otherOptionsSelected = Object.keys(selectedSystemMap).some(
          (k) => k.startsWith(`${questionId}-`) && selectedSystemMap[k].length > 0
        );

        // 仅在没有其他系统选项被勾选的情况下取消该题目的勾选状态
        if (!otherOptionsSelected) {
          const index = answers[questionId].indexOf(option);
          if (index > -1) {
            answers[questionId].splice(index, 1); // 取消该选项的勾选状态
          }
        }
      }
    };

    const getSelectedSystemsForQuestions = () => {
      const questionSystems = {};
      console.log(selectedSystemMap);

      Object.keys(selectedSystemMap).forEach((key) => {
        const [questionId, option] = key.split('-');
        if (option !== 'undefined') {  // 排除键为 undefined 的项
          if (!questionSystems[questionId]) questionSystems[questionId] = {};
          // 仅当数组不为空时添加
          if (selectedSystemMap[key] && selectedSystemMap[key].length > 0) {
            questionSystems[questionId][option] = selectedSystemMap[key];
          }
        }
      });

      // 移除键为 'undefined' 的值
      Object.keys(questionSystems).forEach(key => {
        if (questionSystems[key].hasOwnProperty('undefined')) {
          delete questionSystems[key]['undefined'];
        }
      });

      return questionSystems;
    };


    const handleCheckboxChange = (questionId) => {
      const selectedAnswers = answers[questionId]; // 获取当前问题的已选择答案
      // 检查每个勾选的选项是否有系统选中，如果没有则取消勾选
      selectedAnswers.forEach((option) => {
        const key = `${questionId}-${option}`;
        if (!selectedSystemMap[key] || selectedSystemMap[key].length === 0) {
          const index = answers[questionId].indexOf(option);
          if (index > -1) answers[questionId].splice(index, 1); // 取消该选项的勾选状态
        } else {
          // 如果系统存在，确保选项在数组中
          const index = answers[questionId].indexOf(option);
          if (index === -1) {
            answers[questionId].push(option); // 添加选项以确保勾选状态
          }
        }
      });
    };
    // 滚动到指定元素
    const scrollToElement = (selector) => {
      const element = document.querySelector(selector);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth' });
      }
    };
    const submitAnswers = async () => {

      // 检查每个问题是否已被回答。
      const allQuestionsAnswered = questionnaire.sections.every(section =>
        section.questions.every(question => {
          // 对于复选框问题，确保 answers[question.id] 存在并且有值。
          if (question.type === 'checkbox') {
            // return answers[question.id] && answers[question.id].length > 0;
          }
          return answers[question.id] !== undefined && answers[question.id] !== '';
        })
      );

      if (!allQuestionsAnswered) {
        const unansweredQuestions = questionnaire.sections.flatMap(section =>
          // section.questions.filter(question => !answers[question.id])
          section.questions.filter(question => !answers[question.id] || answers[question.id].length === 0)

        );
        const firstUnansweredQuestion = unansweredQuestions[0];

        if (firstUnansweredQuestion) {
          scrollToElement(`.question-card[data-question-id="${firstUnansweredQuestion.id}"]`); // 滚动到未回答的问题
        }
        ElMessage.warning("请确保每道题都已作答！");
        return;
      }

      // 检查每个选定的系统是否已对每个问题进行评估
      // let missingEvaluations = [];
      // questionnaire.sections.forEach((section) => {
      //   section.questions.forEach((question) => {
      //     // 遍历选定的系统，并检查每个问题的系统是否有对应的评价
      //     parames1.value.selectSystem.forEach((system) => {
      //       const systemEvaluated = Object.keys(selectedSystemMap).some(
      //         (key) => key.startsWith(`${question.id}-`) && selectedSystemMap[key].includes(system)
      //       );
      //       console.log(systemEvaluated);

      //       if (!systemEvaluated) {
      //         missingEvaluations.push(`题目${question.id} 缺少系统【${system}】的评价`);
      //       }
      //     });
      //   });
      // });

      // console.log(missingEvaluations);

      // // 处理缺少的系统评估项
      // if (missingEvaluations.length > 0) {
      //   const firstUnansweredQuestion = document.querySelector(
      //     `.question-card[data-question-id="${missingEvaluations[0].match(/\d+/)[0]}"]`
      //   );
      //   if (firstUnansweredQuestion) {
      //     firstUnansweredQuestion.scrollIntoView({ behavior: 'smooth' });
      //   }

      //   // 显示错误提示框
      //   ElMessageBox.alert(
      //     `<span style='color: red'>提交失败！</span>以下项缺少系统评价:<br>${missingEvaluations.join('<br>')}`,
      //     '错误提示',
      //     {
      //       dangerouslyUseHTMLString: true,
      //       confirmButtonText: '确定',
      //     }
      //   );
      //   return;
      // } else {
      //   console.log('没有缺少的评价。');
      // }

      console.log(answers);
      let answer = ref({});
      // let answer = getSelectedSystemsForQuestions() 
      answer = JSON.parse(JSON.stringify(answers)) // 深拷贝对象
      console.log(answer);
      const payload = {
        value: answer,
        unitName: props.name,
        systemNames: props.companyName, 
        systemIds: props.companyId, 
        remarks: props.textareaValue,
      };

      console.log(payload);
      try {
        const response = await api.post('/system/questionnaire/add', payload);
        if (response.code == 200) {
          ElMessage.success("感谢您的反馈！");
          resetForm();
        } else {
          ElMessage.error("提交失败，请重试！");
        }
      } catch (error) {
        ElMessage.error("提交数据失败:", error);
      }
    };

    // 重置数据
    const resetForm = () => {
      parames.selectCompany = '';
      parames.selectSystem = [];
      parames.textareaValue = '';
      parames1.value.selectSystem = [];
      parames1.value.selectedNames = [];
      Object.keys(answers).forEach(key => delete answers[key]);
      Object.keys(selectedSystemMap).forEach(key => delete selectedSystemMap[key]);
      Object.keys(questionSystemSelections).forEach(key => delete questionSystemSelections[key]);
    };


    const handleDirectSelect = (questionId, option) => {
      answers[questionId] = [option];
    };
    const clearParent = () => {
      emit('clear'); // 触发清空事件
    };
    // 组件挂载后获取数据
    onMounted(() => {
      fetchDataSystem();
      fetchDataCompany();
      // fetchDataAnsers();
    });

    return {
      questionnaire,
      answers,
      submitAnswers,
      parames,
      selectCompanyOption,
      selectSystemOptions,
      selectedSystemMap,
      questionSystemSelections,
      isSystemDisabled,
      updateSystemSelection,
      handleCheckboxChange,
      dataSystem,
      dataCompany,
      handleSelectSystemChange,
      getSelectedSystemsForQuestions,
      handleDirectSelect,
      clearParent,
    };
  },
};
</script>

<style scoped>
.question-card {
  margin-bottom: 20px;
}

.el-checkbox-group {
  display: flex;
  flex-direction: column;
}

.el-radio-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.el-header {
  margin-bottom: 40px;
}

.el-header,
.el-footer {
  text-align: center;
}

.question_description {
  font-weight: bold;
}

.selectsty {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;

  .elselect {
    width: 48%;
    display: flex;
    flex-direction: row;
    align-items: center;
  }

  .elselect span {
    display: inline-block;
    width: 65px;
  }
}

:deep(.popoverSty) {
  background-color: red;
  width: 300px !important;
  max-width: 300px !important;
}

.highlighted {
  background-color: #cce8ff;
  /* 高亮的背景色，可以根据需求调整 */
  color: #0066cc;
  font-weight: bold;
}

.fixed-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  z-index: 1000;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
  padding: 10px 20px;
}

.el-main {
  padding-bottom: 60px;
  /* 根据 footer 的高度调整 */
}
</style>
